<?php

namespace common\repositories\myhtsq;

use common\repositories\common\MyscrmContractSyncDeleteDataRepository;
use Exception;
use common\error\ErrorCode;
use common\support\StringHelper;
use common\repositories\BaseRepository;
use common\models\myhtsq\InvoiceReceivableModel;
use common\entities\myhtsq\InvoiceReceivableEntity;

/**
 * 发票与应收款对应关系仓库
 * @author wangwx 2015-5-12
 */
class InvoiceReceivableRepository extends BaseRepository {

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 保存发票与应收款对应关系
     * @param \common\models\myhtsq\InvoiceReceivableModel $invoiceReceivable
     * @return boolean|string 失败返回false，成功返回关系Id
     */
    public static function saveInvoiceReceivable($invoiceReceivable) {
        try {
            if (isset($invoiceReceivable->invoice_receivable_id) && !empty($invoiceReceivable->invoice_receivable_id)) {
                $entity = InvoiceReceivableEntity::findOne(['invoice_receivable_id' => $invoiceReceivable->invoice_receivable_id]);
            } else {
                $entity = new InvoiceReceivableEntity();
                $entity->invoice_receivable_id = StringHelper::uuid();
            }

            if (!isset($entity)) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_RECEIVABLE_FORM_SAVE_FAIL);
            }
            
            $entity->invoice_id = $invoiceReceivable['invoice_id'];
            $entity->receivable_id = $invoiceReceivable['receivable_id'];
            $entity->cur_billing_amount = $invoiceReceivable['cur_billing_amount'];

            $result = $entity->save();
            if (!$result) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_RECEIVABLE_FORM_SAVE_FAIL);
            }

            return $entity->invoice_receivable_id;
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_RECEIVABLE_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 根据发票ID获取对应的发票与应收款对应关系
     * @param string $invoiceId
     * @return [common\entities\myhtsq\InvoiceReceivableEntity]
     */
    public static function getInvoiceReceivablesByInvoiceId($invoiceId) {
        $query = InvoiceReceivableEntity::find()
                ->where(['invoice_id' => $invoiceId])
                ->all();
        return $query;
    }

    /**
     * 根据应收款ID获取对应的发票与应收款对应关系
     * @param string $receivableId
     * @return [common\entities\myhtsq\InvoiceReceivableEntity]
     */
    public static function getInvoiceReceivablesByReceivableId($receivableId) {
        $query = InvoiceReceivableEntity::find()
                ->where(['receivable_id' => $receivableId])
                ->all();
        return $query;
    }

    /**
     * 根据发票id删除发票与应收款的对应关系
     * @param string $invoiceId
     * @return boolean true/false
     */
    public static function deleteInvoiceReceivableByInvoiceId($invoiceId)
    {
        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

        $deleteData = InvoiceReceivableEntity::findAll(["invoice_id" => $invoiceId]);

        $deleteResult = InvoiceReceivableEntity::deleteAll(['invoice_id' => $invoiceId]);

        if ($deleteResult > 0) {
            foreach ($deleteData as $data) {
                $contractSyncDeleteDataRepository->add('myscrm_invoice_receivable', 'invoice_receivable_id', $data['invoice_receivable_id']);
            }
        }

        return true;
    }

    /**
     * 根据应收款ID获取对应的已开票金额
     * @param string $receivableId
     * @return float
     */
    public static function getTotalBillingAmountByReceivableId($receivableId) {
        $sql = 'select ifnull(sum(cur_billing_amount),0) as totalBillingAmount from myscrm_invoice_receivable where receivable_id =:receivable_id';
        $query = InvoiceReceivableEntity::findBySql($sql,[':receivable_id' => $receivableId])
                ->asArray()
                ->one();
        if (isset($query) && count($query) > 0) {
            return floatval($query['totalBillingAmount']);
        } else {
            return 0;
        }
    }

    /**
     * 根据合同ID获取对应的发票与应收款对应关系
     * @param string $contractId
     * @return array
     */
    public static function getInvoiceReceivablesByContractId($contractId) {
       $query = InvoiceReceivableEntity::find()
                ->select('myscrm_invoice_receivable.*,
                        myscrm_receivable_item.receivable_item_name,
                        myscrm_invoice.invoice_code,myscrm_invoice.invoice_no,myscrm_invoice.invoice_amount,myscrm_invoice.invoice_date,myscrm_invoice.customer_name')
                ->leftJoin('myscrm_contract_receivable', 'myscrm_invoice_receivable.receivable_id = myscrm_contract_receivable.receivable_id')
                ->leftJoin('myscrm_receivable_item', 'myscrm_contract_receivable.receivable_item_id = myscrm_receivable_item.receivable_item_id')
                ->leftJoin('myscrm_invoice', 'myscrm_invoice_receivable.invoice_id = myscrm_invoice.invoice_id')
                ->where(['myscrm_contract_receivable.contract_id' => $contractId])
                ->andWhere(['myscrm_invoice.is_reded_invoice' => 0, 'myscrm_invoice.is_red_invoice' => 0])//红冲与被红冲的发票都不返回
                ->asArray()
                ->all();

        return $query;
       
    }

    /**
     * 根据主键获取发票与应收款对应关系表
     * @param $invoiceReceivableId 主键
     * @return null|static 发票与应收款对应关系表
     */
    public static function getInvoiceReceivableByPK($invoiceReceivableId){
        return InvoiceReceivableEntity::findOne(['invoice_receivable_id'=>$invoiceReceivableId]);
    }
    
    /**
     * 根据发票ID获取应收款信息
     * @param type $invoiceId
     */    
    public static function getReceivableByInvoiceId($invoiceId){
        $query = InvoiceReceivableEntity::find()
            ->select('myscrm_invoice_receivable.*,myscrm_contract_receivable.payee_id')
            ->leftJoin('myscrm_contract_receivable', 'myscrm_invoice_receivable.receivable_id = myscrm_contract_receivable.receivable_id')
            ->where(['myscrm_invoice_receivable.invoice_id' => $invoiceId])
            ->asArray()
            ->all();
        if (!empty($query)) {
            foreach ($query as $k => $v) {
                $query[$k]["payee_name"] = ErpUserRepository::getUserNameByBuguid($v["payee_id"]);
            }
        }
        return $query;
    }


    public static function getBadDebtList()
    {
        return InvoiceReceivableEntity::find()
            ->select('myscrm_invoice_receivable.*')
            ->leftJoin('myscrm_contract_receivable', 'myscrm_contract_receivable.receivable_id=myscrm_invoice_receivable.receivable_id')
            ->where(['myscrm_contract_receivable.is_bad_debt' => 1])
            ->asArray()
            ->all();
    }

}
